import { changeNum } from '@/api/cart.js'
const state = {
  // 存储购物车数据 sku的id  选中状态checked  选中数量count image title price stock
  carlist: []
}
const getters = {
  // 筛选被选中的选项
  checkedItems (state) {
    return state.carlist.filter(item => item.checked === true)
  },
  // 根据选中的选项计算价格
  totalPrice (state, getters) {
    // 对选中的选项进行统计
    return getters.checkedItems.reduce((sum, item) => sum + item.price * item.count, 0)
  },
  checkedAll(state, getters) {
    return state.carlist.length === getters.checkedItems.length
  }
}
const mutations = {
  addToCart(state, payload) {
    state.carlist.push(payload)
  },
  clear (state) {
    state.carlist = []
  },
  checkedChange(state, { id, checked }) {
    // state.carlist.find(item => item.id === id).checked === checked
    const sameId = state.carlist.find(item => item.id === id)
    sameId.checked = checked
  },
  countChanged(state, {id, count}) {
    // state.carlist.find(item => item.id === id).checked === checked
    const sameId = state.carlist.find(item => item.id === id)
    sameId.count= count
  },
  changeAll(state, { checked }){
    state.carlist.forEach(item => item.checked =checked)
  }
}
const actions = {
  async countChanged({commit}, payload){
    commit('countChanged', payload)
    const { data } = await changeNum({
      id: payload.id,
      number: payload.count
    })  
    if (data.status !== 200) { return }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}